_base_ = [
    '../_base_/datasets/dota.py',
    '../_base_/schedules/schedule_2x.py',
    '../../_base_/default_runtime.py'
]
fp16 = dict(loss_scale=512.)
model = dict(
    type='OrientedRCNN',
    pretrained='torchvision://resnet50',
    backbone=dict(
        type='ResNet',
        depth=50,
        num_stages=4,
        out_indices=(0, 1, 2, 3),
        frozen_stages=1,
        norm_cfg=dict(type='BN', requires_grad=True),
        norm_eval=True,
        style='pytorch'),
    neck=dict(
        type='FPN',
        in_channels=[256, 512, 1024, 2048],
        out_channels=256,
        num_outs=5),
    rpn_head=dict(
        type='AngleClsRPNHead',
        in_channels=256,
        onehot_dim=60,
        feat_channels=256,
        anchor_generator=dict(
            type='AnchorGenerator',
            scales=[8],
            ratios=[0.5, 1.0, 2.0],
            strides=[4, 8, 16, 32, 64]),
        bbox_coder=dict(
            type='AngleCoder',
            target_means=[.0, .0, .0, .0],
            target_stds=[1.0, 1.0, 1.0, 1.0]),
        loss_cls=dict(
            type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
        loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
    roi_head=dict(
        type='OBBStandardRoIHead',
        bbox_roi_extractor=dict(
            type='OBBSingleRoIExtractor',
            roi_layer=dict(type='RoIAlignRotated', out_size=7, sample_num=2),
            out_channels=256,
            extend_factor=(1.4, 1.2),  # 应该是对roi的w和h(先后我还不确定)放缩的参数最后得到roi。
            featmap_strides=[4, 8, 16, 32]),
        bbox_head=dict(
            type='OBBShared2FCBBoxHead',
            start_bbox_type='obb',
            end_bbox_type='obb',
            in_channels=256,
            fc_out_channels=1024,
            roi_feat_size=7,
            num_classes=15,
            bbox_coder=dict(
                type='OBB2OBBDeltaXYWHTCoder',
                target_means=[0., 0., 0., 0., 0.],
                target_stds=[0.1, 0.1, 0.2, 0.2, 0.1]),
            reg_class_agnostic=True,
            loss_cls=dict(
                type='CrossEntropyLoss',
                use_sigmoid=False,
                loss_weight=1.0),
            loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
                           loss_weight=1.0))))
# model training and testing settings
train_cfg = dict(
    rpn=dict(
        assigner=dict(
            type='MaxIoUAssigner',
            pos_iou_thr=0.7,
            neg_iou_thr=0.3,
            min_pos_iou=0.3,
            match_low_quality=True,
            gpu_assign_thr=200,
            ignore_iof_thr=-1),
        sampler=dict(
            type='RandomSampler',
            num=256,
            pos_fraction=0.5,
            neg_pos_ub=-1,
            add_gt_as_proposals=False),
        allowed_border=0,
        pos_weight=-1,
        debug=False),
    rpn_proposal=dict(
        nms_across_levels=False,
        nms_pre=2000,
        nms_post=2000,
        max_num=2000,
        nms_thr=0.8,
        min_bbox_size=0),
    rcnn=dict(
        assigner=dict(
            type='MaxIoUAssigner',
            pos_iou_thr=0.5,
            neg_iou_thr=0.5,
            min_pos_iou=0.5,
            match_low_quality=False,
            ignore_iof_thr=-1,
            iou_calculator=dict(type='OBBOverlaps')),
        sampler=dict(
            type='OBBRandomSampler',
            num=512,
            pos_fraction=0.25,
            neg_pos_ub=-1,
            add_gt_as_proposals=True),
        pos_weight=-1,
        debug=False))
test_cfg = dict(
    rpn=dict(
        nms_across_levels=False,
        nms_pre=2000,
        nms_post=2000,
        max_num=2000,
        nms_thr=0.8,
        min_bbox_size=0),
    rcnn=dict(
        score_thr=0.05, nms=dict(type='obb_nms', iou_thr=0.1), max_per_img=2000))


# def _get_bboxes_single(self,
#                        cls_score_list,
#                        bbox_pred_list,
#                        angle_pred_list,
#                        mlvl_anchors,
#                        img_shape,
#                        scale_factor,
#                        cfg,
#                        rescale=False):
#     """Transform outputs for a single batch item into bbox predictions.
#
#     Args:
#         cls_score_list (list[Tensor]): Box scores for a single scale level
#             Has shape (num_anchors * num_classes, H, W).
#         bbox_pred_list (list[Tensor]): Box energies / deltas for a single
#             scale level with shape (num_anchors * 4, H, W).
#         mlvl_anchors (list[Tensor]): Box reference for a single scale level
#             with shape (num_total_anchors, 4).
#         img_shape (tuple[int]): Shape of the input image,
#             (height, width, 3).
#         scale_factor (ndarray): Scale factor of the image arange as
#             (w_scale, h_scale, w_scale, h_scale).
#         cfg (mmcv.Config): Test / postprocessing configuration,
#             if None, test_cfg would be used.
#         rescale (bool): If True, return boxes in original image space.
#
#     Returns:
#         Tensor: Labeled boxes in shape (n, 5), where the first 4 columns
#             are bounding box positions (tl_x, tl_y, br_x, br_y) and the
#             5-th column is a score between 0 and 1.
#     """
#     cfg = self.test_cfg if cfg is None else cfg
#     assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors) == len(angle_pred_list)
#     mlvl_bboxes = []
#     mlvl_scores = []
#     for cls_score, bbox_pred, angle_pred, anchors in zip(cls_score_list,  # cls_score:(n_base_anchor*n_classes,H,W)
#                                                          bbox_pred_list, angle_pred_list, mlvl_anchors):
#         assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
#         cls_score = cls_score.permute(1, 2,  # -> (H,W,n_base_anchor*n_classes)-> (H*W*n_base_anchor,n_classes)
#                                       0).reshape(-1, self.cls_out_channels)
#         if self.use_sigmoid_cls:
#             scores = cls_score.sigmoid()
#         else:
#             scores = cls_score.softmax(-1)
#         bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, self.reg_dim)  # (H*W*n_base_anchor,4)
#         angle_pred = angle_pred.permute(1, 2, 0).reshape(-1, self.onehot_dim)  # (H*W*n_base_anchor,onehot_dim)
#         nms_pre = cfg.get('nms_pre', -1)
#         if nms_pre > 0 and scores.shape[0] > nms_pre:
#             # Get maximum scores for foreground classes.
#             if self.use_sigmoid_cls:
#                 max_scores, _ = scores.max(dim=1)
#             else:
#                 # remind that we set FG labels to [0, num_class-1]
#                 # since mmdet v2.0
#                 # BG cat_id: num_class
#                 max_scores, _ = scores[:, :-1].max(dim=1)
#             _, topk_inds = max_scores.topk(nms_pre)
#             anchors = anchors[topk_inds, :]
#             bbox_pred = bbox_pred[topk_inds, :]
#             angle_pred = angle_pred[topk_inds, :]
#             scores = scores[topk_inds, :]
#         bboxes = self.bbox_coder.decode(
#             anchors, bbox_pred, angle_pred, max_shape=img_shape)
#         mlvl_bboxes.append(bboxes)
#         mlvl_scores.append(scores)
#     mlvl_bboxes = torch.cat(mlvl_bboxes)
#     if rescale:
#         scale_factor = mlvl_bboxes.new_tensor(scale_factor)
#         if self.bbox_type == 'hbb':
#             mlvl_bboxes /= scale_factor
#         elif self.bbox_type == 'obb':
#             mlvl_bboxes[..., :4] = mlvl_bboxes[..., :4] / scale_factor
#         elif self.bbox_type == 'poly':
#             mlvl_bboxes /= scale_factor.repeat(2)
#         else:
#             raise NotImplementedError
#     mlvl_scores = torch.cat(mlvl_scores)
#     if self.use_sigmoid_cls:
#         # Add a dummy background class to the backend when using sigmoid
#         # remind that we set FG labels to [0, num_class-1] since mmdet v2.0
#         # BG cat_id: num_class
#         padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
#         mlvl_scores = torch.cat([mlvl_scores, padding], dim=1)
#
#     det_bboxes, det_labels = multiclass_arb_nms(mlvl_bboxes, mlvl_scores,
#                                                 cfg.score_thr, cfg.nms,
#                                                 cfg.max_per_img,
#                                                 bbox_type=self.bbox_type)
#     return det_bboxes, det_labels
